package cn.e4j.modular.api.controller;

import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.LocalDateUtils;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.FhpsService;
import cn.e4j.modular.api.util.CommonUtils;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.crm.entity.GwaklT;
import cn.e4j.modular.crm.entity.GwamT;
import cn.e4j.modular.crm.entity.GwcuT;
import cn.e4j.modular.crm.entity.MmraT;
import cn.e4j.modular.crm.mapper.GwaklTMapper;
import cn.e4j.modular.crm.mapper.GwamTMapper;
import cn.e4j.modular.system.entity.SysUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("api/wx/fhps")
public class FhpsController extends ControllerSupport {
    @Autowired
    FhpsService fhpsService;
    
    @Autowired
    GwaklTMapper gwaklTMapper;

    @Autowired
    GwamTMapper gwamTMapper;

    @RequestMapping("getCompany")
    public ResponseData getCompany(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        SysUser user = wapper.getSysUser();
        try {
            inDto.put("GWCUUSER",user.getID());
            inDto.put("GWCUENT",inDto.getString("ENT"));
            list = fhpsService.getCompany(inDto);
        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(list);
    }

    @RequestMapping("check")
    public ResponseData check(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        Dto queryDto = new Dto();
        Dto outDto = new Dto();
        try {

            Integer already = fhpsService.getAlready(inDto);
            Dto res = fhpsService.getTotal(inDto);
            List<Dto> detail = fhpsService.getDetail(inDto);
            Integer validateProductNoInKC = fhpsService.validateProductNoInKC(inDto);
            Integer ValidateOrderNoInOrder = fhpsService.ValidateOrderNoInOrder(inDto);
            Integer ValidateProductNoInOrder = fhpsService.ValidateProductNoInOrder(inDto);
            Integer ValidateProductInMmra = fhpsService.ValidateProductInMmra(inDto);

            queryDto.put("GWCSDOCNO",inDto.getString("orderNo"));
            queryDto.put("GWCS001",inDto.getString("productNo"));
            List<Dto> list = fhpsService.getOrderList(queryDto);
            outDto.put("GWCS002","");
            Dto gwcs_tPO = new Dto();
            if (ToolUtil.isNotEmpty(list)){
                gwcs_tPO = list.get(0);
                outDto.put("GWCS002",gwcs_tPO==null?"":gwcs_tPO.getString("GWCS002"));//销售单位
            }else {
                Dto dto = new Dto();
                dto.put("GWCSDOCNO",inDto.getString("orderNo"));
                list = fhpsService.getOrderList(dto);
                if (ToolUtil.isNotEmpty(list)){
                    gwcs_tPO = list.get(0);
                }
            }
            String gwcsmlegal = gwcs_tPO.getString("GWCSMLEGAL");
            String GWCS010 = gwcs_tPO.getString("GWCS010");
            QueryWrapper<GwaklT> gwaklTQueryWrapper = new QueryWrapper<>();
            gwaklTQueryWrapper.eq("GWAKLENT",inDto.getString("ENT"));
            gwaklTQueryWrapper.eq("GWAKL001",GWCS010);
            GwaklT po = gwaklTMapper.selectOne(gwaklTQueryWrapper);

            outDto.put("ProductNoIsInKC",(validateProductNoInKC!=null && validateProductNoInKC>0)?true:false);
            outDto.put("OrderNoIsInOrder",(ValidateOrderNoInOrder!=null && ValidateOrderNoInOrder>0)?true:false);
            outDto.put("ProductNoIsInOrder",(ValidateProductNoInOrder!=null && ValidateProductNoInOrder>0)?true:false);
            outDto.put("ValidateProductInMmra",(ValidateProductInMmra!=null && ValidateProductInMmra>0)?true:false);

            if (!outDto.getBoolean("ProductNoIsInKC") || !outDto.getBoolean("OrderNoIsInOrder") || !outDto.getBoolean("ProductNoIsInOrder"))
                return SUCCESS(outDto);

            outDto.put("already",already==null?0:already);
            outDto.put("total",res.getInteger("TOTAL"));
            outDto.put("GWCS010",GWCS010==null?"":GWCS010);
            outDto.put("GWCSMLEGAL",gwcsmlegal==null?" ":gwcsmlegal);
            outDto.put("GWCS014",gwcs_tPO.getString("GWCS014"));//业务员
            outDto.put("GWCS015",gwcs_tPO.getString("GWCS015"));//业务员手机
            //t1.GWCS008,t2.gwaml003,t2.gwaml004
            if (detail!=null && detail.size()>0){
                Dto dto = detail.get(0);
                outDto.put("customerName",po==null?"":po.getGWAKL003());
                outDto.put("productName",(dto==null || ToolUtil.isEmpty(dto.getString("GWAML003"))?"-":dto.getString("GWAML003")));
                outDto.put("spec",(dto==null || ToolUtil.isEmpty(dto.getString("GWAML004"))?"-":dto.getString("GWAML004")));
            }

        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(outDto);
    }

    @RequestMapping("save")
    public ResponseData save(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        SysUser user = wapper.getSysUser();
        LocalDate now = LocalDate.now();
        Dto outDto = new Dto();
        try {
            JSONArray list = JSONArray.parseArray(inDto.getString("list"));

            List<GwcuT> seqList = getSeqList(list, user);
            List<MmraT> mmraTPOS = new ArrayList<>();
            for (int i=0;i<seqList.size();i++){
                JSONObject jsonObject = list.getJSONObject(i);
                GwcuT gwcu = seqList.get(i);

                gwcu.setGWCU003(jsonObject.getString("GWCS002"));//set销售单位
                //客户设备档
                MmraT po = new MmraT();
                po.setMMRAENT(user.getDBC());
                po.setMMRA001(jsonObject.getString("GWCS010"));
                po.setMMRA002(gwcu.getGWCU001());
                po.setMMRA003(gwcu.getGWCU002());
                po.setMMRA004(jsonObject.getString("productName"));
                //获取设备类型
                QueryWrapper<GwamT> gwamTQueryWrapper = new QueryWrapper<>();
                gwamTQueryWrapper.eq("GWAM001", po.getMMRA002());
                GwamT gwam = gwamTMapper.selectOne(gwamTQueryWrapper);
                po.setMMRA007(ToolUtil.isNotEmpty(gwam)?gwam.getGWAM007():"-");
                po.setMMRA009(jsonObject.getString("orderNo"));
                po.setMMRA010(now);
                po.setMMRA011(now);
                po.setMMRA013("1");
                po.setMMRA014("1");
                po.setMMRA017(jsonObject.getString("GWCSMLEGAL"));
                po.setMMRA006(jsonObject.getString("spec"));//规格
                String gwam012 = (gwam==null || gwam.getGWAM012()==null?"0":gwam.getGWAM012());//保固月数
                String gwam013 = (gwam==null || gwam.getGWAM013()==null?"0":gwam.getGWAM013());//保固天数
                Date varDate = DateUtils.addMonths(new Date(),Integer.parseInt(gwam012));
                Date threeDays = DateUtils.addDays(varDate, Integer.parseInt(gwam013));
                po.setMMRA012(LocalDateUtils.dateToLocalDate(threeDays));//三包到期日期计算
                po.setMMRAACTI("Y");
                po.setMMRAUSER(user.getACCOUNT());
                po.setMMRAGRUP(user.getORG_ID());
                po.setMMRATIME(DateUtils.getTime());
                po.setMMRADATE(now);

                //添加业务员信息
                po.setMMRA042(jsonObject.getString("GWCS014"));
                po.setMMRA043(jsonObject.getString("GWCS015"));

                mmraTPOS.add(po);
            }
            fhpsService.save(seqList,mmraTPOS);

            inDto.put("GWCUUSER",user.getID());
            inDto.put("GWCUENT",inDto.getString("ENT"));
            outDto.put("selectList",fhpsService.getCompany(inDto));

        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(outDto);
    }

    //将多个品类的单子设置项序,并返回处理后的list
    private List<GwcuT> getSeqList(JSONArray list,SysUser user) {
        String temp = "";
        List<GwcuT> gwcuts = new ArrayList<>();
        Date date = new Date();
        for (int i = 0;i<list.size();i++){
            Dto queryDto = new Dto();
            JSONObject jsonObject = list.getJSONObject(i);
//            Integer count = jsonObject.getInteger("count");
            String productNo = jsonObject.getString("productNo");
            String orderNo = jsonObject.getString("orderNo");

            queryDto.put("productNo",productNo);
            queryDto.put("orderNo",orderNo);
            Integer maxSeq = fhpsService.getMaxSeq(queryDto);
            maxSeq = (maxSeq == null?0:maxSeq);

            temp +=(productNo+",");
            Integer seq = temp.split(productNo).length;
            jsonObject.put("GWCUSEQ",maxSeq+seq);

            GwcuT gwcuTPO = CommonUtils.toJavaClass(jsonObject,GwcuT.class);
            gwcuTPO.setGWCUDOCNO("YSDH" + DateUtils.getDate("yyyyMMddHHmmssSSS"));
            //gwcuTPO.setGWCUDOCDATE(date);
            gwcuTPO.setGWCUENT(user.getDBC());
            gwcuTPO.setGWCUDOCDATE(LocalDate.now());
            gwcuTPO.setGWCUUSER(user.getID());
            gwcuTPO.setGWCUGRUP(user.getORG_ID());
            gwcuTPO.setGWCUDATE(LocalDate.now());
            gwcuTPO.setGWCUTIME(DateUtils.formatDate(date, "HH:mm:ss"));
            gwcuTPO.setGWCUORIG(user.getORG_ID());
            gwcuTPO.setGWCUORIU(user.getID());
            gwcuTPO.setGWCUACTI("N");
            gwcuts.add(gwcuTPO);
        }

        return gwcuts;
    }

}
